package com.mfoyou.agent.web.controller.account;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import org.mfoyou.agent.common.dao.domain.HuawuAgentInfo;
import org.mfoyou.agent.common.dao.domain.HuawuAgentStoreSetting;
import org.mfoyou.agent.common.dao.domain.HuawuServiceComponent;
import org.mfoyou.agent.common.dao.domain.HuawuServiceNotice;
import org.mfoyou.agent.common.dao.domain.HuawuServiceOrder;
import org.mfoyou.agent.common.dao.domain.HuawuServicePrice;
import org.mfoyou.agent.common.dao.domain.HuawuUser;
import org.mfoyou.agent.common.dao.domain.HuawuWorker;
import org.mfoyou.agent.common.dao.domain.MfoyouRegionCustom;
import org.mfoyou.agent.common.dao.domain.MfoyouStationMaster;
import org.mfoyou.agent.common.entity.enums.MfoyouUserType;
import org.mfoyou.agent.common.inf.IAccount;
import org.mfoyou.agent.common.inf.IIdentity;
import org.mfoyou.agent.common.inf.IOrder;
import org.mfoyou.agent.utils.common.DateUtils;
import org.mfoyou.agent.utils.common.JsonRet;
import org.mfoyou.agent.utils.common.ListObject;
import org.mfoyou.agent.utils.common.Logger;
import org.mfoyou.agent.utils.common.MfoyouMap;
import org.mfoyou.agent.utils.common.StrUtil;
import org.mfoyou.agent.utils.json.Json2Object;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.mfoyou.agent.web.intercepter.UrlRight;
import com.mfoyou.agent.web.intercepter.UserRight;
import com.mfoyou.agent.web.service.account.AccountService;
import com.mfoyou.agent.web.service.account.AgentService;
import com.mfoyou.agent.web.service.common.GeoService;
import com.mfoyou.agent.web.service.order.OrderRunnerService;
import com.mfoyou.agent.web.service.order.ServiceOrderService;
import com.mfoyou.agent.web.service.session.SessionService;
import com.mfoyou.agent.web.service.thirdPart.XGPushSerivce;

/**
 * 代理商controller
 *
 * @author hzhang7
 */
@Path("agent")
@Service
public class AgentController {

    private static final Logger logger = Logger.getLogger(AgentController.class);

    @Autowired
    SessionService sessionService;

    @Autowired
    IIdentity iIdentity;

    @Autowired
    IAccount iAccount;

    @Autowired
    AgentService agentService;

    @Autowired
    IOrder iOrder;

    @Autowired
    OrderRunnerService orderRunnerService;

    @Autowired

    ServiceOrderService serviceOrderService;

    @Autowired
    XGPushSerivce xgPushSerivce;

    @Autowired
    AccountService accountService;

    @Autowired
    GeoService geoService;

    /**
     * 获取本人服务商信息
     *
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path(value = "myinfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> myinfo(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Integer userId = sessionService.currentUserId(request);
        if (sessionService.currentUserType(request) == UserRight.AGENTACCESS.getValue()) {
            HuawuAgentInfo mfoyouAgent = iIdentity.getAgentInfo(userId);
            if (mfoyouAgent == null) {
                return JsonRet.buildRet(-98);
            }
            return JsonRet.buildRet(0, mfoyouAgent);
        }
        MfoyouStationMaster stationMasterByUserId = iIdentity.getStationMasterByUserId(userId);
        if (stationMasterByUserId != null) {
            Integer agentId = stationMasterByUserId.getAgentId();
            String agentName = iIdentity.getAgentInfo(agentId).getAgentName();
            stationMasterByUserId.setAgentName(agentName);
        }
        return JsonRet.buildRet(0, stationMasterByUserId);
    }

    /**
     * 修改代理信息
     *
     * @param request
     * @param response
     * @param json
     * @return
     */
    @POST
    @Path(value = "modify/myinfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> applyModify(@Context HttpServletRequest request, @Context HttpServletResponse response, String json) {
        MfoyouMap mfoyouMap = Json2Object.json2MfoyouMap(json);
        if (mfoyouMap == null || mfoyouMap.size() == 0)
            return JsonRet.buildRet(-99);
        if (mfoyouMap.get("agentTeamName") != null || mfoyouMap.get("agentContactsName") != null || mfoyouMap.get("agentContactsPhone") != null) {
            HuawuAgentInfo mfoyouAgent = new HuawuAgentInfo();
            mfoyouAgent.setAgentId(sessionService.currentUserAgentId(request));
            mfoyouAgent.setAgentName(mfoyouMap.get("agentTeamName"));
            mfoyouAgent.setAgentUserContacts(mfoyouMap.get("agentContactsName"));
            mfoyouAgent.setAgentPhone(mfoyouMap.get("agentContactsPhone"));
            iIdentity.modifyMfoyouAgent(mfoyouAgent);
        }
        if (mfoyouMap.get("userHeadUrl") != null) {
            HuawuUser mfoyouUser = new HuawuUser();
            mfoyouUser.setUserId(sessionService.currentUserId(request));
            mfoyouUser.setUserHeadUrl(mfoyouMap.get("userHeadUrl"));
            iAccount.modifyUser(mfoyouUser);
        }
        return JsonRet.buildRet(0);
    }

    /**
     * 指派订单
     *
     * @param request
     * @param response
     * @param orderId   订单id
     * @param userId    跑腿小哥id
     * @return
     */
    @POST
    @Path(value = "/gain/{userId}/{orderId}")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> runerGain(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("orderId") Integer orderId, @PathParam("userId") Integer userId) {
        Boolean bRet = serviceOrderService.gainOrder(request, userId, orderId);
        if (bRet) {
            xgPushSerivce.pushNoticeUser(userId, orderId, 1, "已接新订单提醒", "获取到团队指派的新订单，请及时查看");
        }
        return JsonRet.buildRet(bRet ? 0 : -92, bRet);
    }

    /**
     * 骑手列表
     *
     * @param request
     * @param response
     * @param pageId
     * @param pageSize
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "/runer/list")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> runerList(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("pageId") Integer pageId,
                                @QueryParam("pageSize") Integer pageSize) throws ParseException {
        Date startDate = DateUtils.parse(request.getParameter("startDate"));
        Date endDate = DateUtils.parse(request.getParameter("endDate"));
        HuawuWorker mfoyouWorker = new HuawuWorker();
        mfoyouWorker.setAgentId(sessionService.currentUserAgentId(request));
        mfoyouWorker.setWorkerOpenState(StrUtil.parseInteger(request.getParameter("openState")));
        mfoyouWorker.setWorkerPhone(request.getParameter("phone"));
        mfoyouWorker.setWorkerState(StrUtil.parseInteger(request.getParameter("state")));
        return JsonRet.buildSuccRet(ListObject.BulidListObject(iIdentity.getMfoyouWorkerList(mfoyouWorker, pageId, pageSize, startDate, endDate)));
    }

    /**
     * 查询服务商信息
     *
     * @param request
     * @param response
     * @param agentId
     * @return
     * @throws ParseException
     */
    @GET
    @Path("info/{agentId}")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.ADMINACCESS, UserRight.RUNERACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> info(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("agentId") Integer agentId) throws ParseException {
        HuawuAgentInfo mfoyouAgent = iIdentity.getAgentInfo(agentId);
        HuawuAgentStoreSetting huawuAgentStoreSetting = iIdentity.getSpecialSettingV1(agentId);
        if (huawuAgentStoreSetting != null) {
            mfoyouAgent.setAgentPhone(huawuAgentStoreSetting.getPhone());
        }
        if (mfoyouAgent == null) {
            return JsonRet.buildRet(-98);
        } else {
            return JsonRet.buildRet(0, mfoyouAgent);
        }
    }

    /**
     * 跑腿员信息
     *
     * @param request
     * @param response
     * @param pageId
     * @param pageSize
     * @param startDate
     * @param endDate
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "/runer/listv2")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> runerListV2(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                  @QueryParam("pageId") Integer pageId,
                                  @QueryParam("pageSize") Integer pageSize,
                                  @QueryParam("startDate") String startDate,
                                  @QueryParam("endDate") String endDate) throws ParseException {
        Date sdate = null;
        Date eDate = null;
        if (startDate == null || endDate == null) {
            eDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -1);
            sdate = calendar.getTime();
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            sdate = simpleDateFormat.parse(startDate);
            eDate = simpleDateFormat.parse(endDate);
        }
        HuawuWorker mfoyouWorker = new HuawuWorker();
        Integer userId = sessionService.currentUserId(request);
        if (sessionService.currentUserType(request).intValue() == UserRight.AGENTACCESS.getValue()) {
            mfoyouWorker.setAgentId(userId);
        } else {
            mfoyouWorker.setStationId(sessionService.currentUserId(request));
        }
        mfoyouWorker.setWorkerOpenState(StrUtil.parseInteger(request.getParameter("openState")));
        mfoyouWorker.setWorkerPhone(request.getParameter("phone"));
        mfoyouWorker.setWorkerState(StrUtil.parseInteger(request.getParameter("state")));
        return JsonRet.buildSuccRet(ListObject.BulidListObject(agentService.getMfoyouWorkerListV2(mfoyouWorker, pageId, pageSize, sdate, eDate)));
    }

    /**
     * 跑腿员列表
     *
     * @param request
     * @param response
     * @param pageId
     * @param pageSize
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "/runer/listV3")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> runerListV3(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("pageId") Integer pageId,
                                  @QueryParam("pageSize") Integer pageSize) throws ParseException {
        HuawuWorker mfoyouWorker = new HuawuWorker();
        if (sessionService.currentUserType(request).intValue() == MfoyouUserType.agent.getValue()) {
            mfoyouWorker.setAgentId(sessionService.currentUserId(request));
        } else {
            mfoyouWorker.setStationId(sessionService.currentUserId(request));
        }
        mfoyouWorker.setWorkerOpenState(StrUtil.parseInteger(request.getParameter("openState")));
        mfoyouWorker.setWorkerPhone(request.getParameter("phone"));
        return JsonRet.buildSuccRet(ListObject.BulidListObject(agentService.getMfoyouWorkerListV3(mfoyouWorker, pageId, pageSize)));
    }

    /**
     * 我的价格配置: 获取配送计费规则
     *
     * @param request
     * @param response
     * @return
     * @throws ParseException
     */
    @GET
    @Path(value = "/my/configure/price/listV2")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> myConfigurePriceListV2(@Context HttpServletRequest request, @Context HttpServletResponse response) throws ParseException {
        Integer agentId = sessionService.currentUserId(request);
        HuawuServicePrice mfoyouServicePricev2 = agentService.getConfigurePrice(agentId, true);
        return JsonRet.buildSuccRet(mfoyouServicePricev2);
    }

    /**
     * 保存配送计费规则
     *
     * @param request
     * @param response
     * @param json
     * @return
     */
    @POST
    @Path(value = "/configure/priceV2")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS})
    public JsonRet<?> configurePricev2(@Context HttpServletRequest request, @Context HttpServletResponse response, String json) {
        if (json == null)
            return JsonRet.buildRet(-99);
        Integer agentId = sessionService.currentUserId(request);
        HuawuServicePrice mfoyouServicePricev2 = Json2Object.json2Object(json, HuawuServicePrice.class);
        mfoyouServicePricev2.setAgentId(agentId);
        int ret = agentService.updatePriceV2ByagentId(mfoyouServicePricev2);
        return ret == 1 ? JsonRet.buildRet(0) : JsonRet.buildRet(-95);
    }

    /**
     * 获取订单周围人
     *
     * @param request
     * @param response
     * @param orderId
     * @param ownUserId
     * @param pageId
     * @param pageSize
     * @return
     */
    @GET
    @Path(value = "/runer/pickup")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> runerPickup(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("orderId") Integer orderId
            , @QueryParam("userId") Integer ownUserId, @QueryParam("pageId") Integer pageId, @QueryParam("pageSize") Integer pageSize) {
        HuawuServiceOrder order = iOrder.getServiceOrderInfo(orderId);
        if (request.getParameter("type") != null && request.getParameter("type").equals("1")) {
            order.setServiceOrderSource(-2);
        }
        return JsonRet.buildRet(0, orderRunnerService.orderMatchAgentRunner(order, ownUserId));
    }

    /**
     * 编辑接单员
     *
     * @param request
     * @param response
     * @param json
     * @return
     */
    @POST
    @Path(value = "modify/worker")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS})
    public JsonRet<?> modifyWorker(@Context HttpServletRequest request, @Context HttpServletResponse response, String json) {
        MfoyouMap map = Json2Object.json2MfoyouMap(json);
        Integer workerid = map.getInteger("workerId");
        if (workerid == null) {
            return JsonRet.buildRet(-96);
        }
        HuawuWorker mfoyouWorker = new HuawuWorker();
        mfoyouWorker.setUserId(workerid);
        Integer fee = map.getInteger("fee");
        Integer stationId = map.getInteger("stationId");
        mfoyouWorker.setWorkerFee(fee);
        mfoyouWorker.setStationId(stationId);
        int modifyMfoyouWorkerInfo = iIdentity.modifyMfoyouWorkerInfo(mfoyouWorker);
        if (modifyMfoyouWorkerInfo == 1) {
            accountService.modifyHuawuWorkerStationId(workerid, stationId);
        }
        return JsonRet.buildRet(modifyMfoyouWorkerInfo - 1);
    }

    /**
     * 添加跑腿员 用电话
     *
     * @param request
     * @param response
     * @param userPhone
     * @return
     */
    @POST
    @Path(value = "addruner/{userPhone}")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> addWorker(@Context HttpServletRequest request, @Context HttpServletResponse response
            , @PathParam("userPhone") String userPhone) {
        if (userPhone == null)
            return JsonRet.buildRet(-96);
        Integer agentId = sessionService.currentUserId(request);
        HuawuUser userInfo = iAccount.getUserInfoByPhoneV2(userPhone, agentId);
        if (userInfo == null) {
            return JsonRet.buildFailRet("此用户不存在。");
        }
        HuawuWorker mfoyouWorker = iIdentity.getMfoyouWorkerInfoV2(userInfo.getUserId(), agentId);
        if (mfoyouWorker == null || mfoyouWorker.getAgentId() != null) {
            return JsonRet.buildRet(-87);
        }
        HuawuWorker huawuWorker = new HuawuWorker();
        if (sessionService.currentUserType(request) == UserRight.STATIONMASTER.getValue()) {
            huawuWorker.setAgentId(sessionService.currentUserAgentId(request));
            huawuWorker.setStationId(sessionService.currentUserId(request));
        } else {
            huawuWorker.setAgentId(sessionService.currentUserId(request));
        }
        huawuWorker.setUserId(mfoyouWorker.getUserId());
        huawuWorker.setJoinTime(new Date());
        int modifyMfoyouWorkerInfo = iIdentity.modifyMfoyouWorkerInfo(huawuWorker);
        sessionService.modifyWorkerAgent(sessionService.currentUserId(request), mfoyouWorker.getUserId());
        return JsonRet.buildRet(modifyMfoyouWorkerInfo - 1);
    }

    /**
     * 获取设置
     *
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("get/setting")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> getSpecialSetting(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Integer agentId = sessionService.currentUserId(request);
        HuawuAgentStoreSetting setting = iIdentity.getSpecialSettingV1(agentId);
        return JsonRet.buildSuccRet(setting);
    }

    /**
     * 设置服务商配置信息
     *
     * @param request
     * @param response
     * @param json
     * @return
     */
    @POST
    @Path("setting")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> settingThird(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                   String json) {
        MfoyouMap json2MfoyouMap = Json2Object.json2MfoyouMap(json);
        Integer agentId = sessionService.currentUserId(request);
        HuawuAgentStoreSetting mfoyouAgentStoreSetting = new HuawuAgentStoreSetting();
        mfoyouAgentStoreSetting.setAgentId(agentId);
        mfoyouAgentStoreSetting.setStoreName(json2MfoyouMap.get("storeName"));
        mfoyouAgentStoreSetting.setStoreLogoUrl(json2MfoyouMap.get("storeLogo"));
        mfoyouAgentStoreSetting.setServiceName(json2MfoyouMap.get("serviceName"));
        mfoyouAgentStoreSetting.setServiceLogo(json2MfoyouMap.get("serviceLogo"));
        mfoyouAgentStoreSetting.setPhone(json2MfoyouMap.get("phone"));
        mfoyouAgentStoreSetting.setStoreNotifycation(json2MfoyouMap.get("storeNotifycation"));
        mfoyouAgentStoreSetting.setNotifyIsClose(json2MfoyouMap.getInteger("notifyIsClose"));
        Integer rechageType = json2MfoyouMap.getInteger("rechageType");
        mfoyouAgentStoreSetting.setStorePhone(json2MfoyouMap.get("storePhone"));
        mfoyouAgentStoreSetting.setRechageType(rechageType);
        logger.info(rechageType + "");
        int result = iIdentity.updateMfoyouAgentSetting(mfoyouAgentStoreSetting);
        return result == 1 ? JsonRet.buildRet(0) : JsonRet.buildRet(-11);
    }

    /**
     * 获取统计数据
     *
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path(value = "gethomedata")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> gethomedata(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Integer agenid = sessionService.currentUserId(request);
        int userType = 1;
        if (sessionService.currentUserType(request).intValue() == UserRight.STATIONMASTER.getValue()) {
            userType = 0;
        }
        HashMap<String, Object> hashMap = agentService.getAgentMoneyDate(agenid, userType);
        return JsonRet.buildSuccRet(hashMap);
    }

    /**
     * 解雇接单员
     *
     * @param request
     * @param workerId
     * @param state
     * @return
     */
    @GET
    @Path(value = "dismissWorker")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> dismissWorker(@Context HttpServletRequest request, @QueryParam("workerId") Integer workerId, @QueryParam("state") Integer state) {
        HuawuWorker mfoyouWorkerInfo = iIdentity.getMfoyouWorkerInfo(workerId, null);
        if (mfoyouWorkerInfo == null) {
            return JsonRet.buildRet(-52);
        }
        if (sessionService.currentUserType(request) == UserRight.STATIONMASTER.getValue()) {
            if (mfoyouWorkerInfo.getStationId() == null || !mfoyouWorkerInfo.getStationId().equals(sessionService.currentUserId(request))) {
                return JsonRet.buildRet(-53);
            }
            Integer currentUserAgentId = sessionService.currentUserAgentId(request);
            geoService.removeRunnerPos(currentUserAgentId, workerId);
        } else {
            Integer agenid = sessionService.currentUserId(request);
            if (mfoyouWorkerInfo.getAgentId() == null || !mfoyouWorkerInfo.getAgentId().equals(agenid)) {
                return JsonRet.buildRet(-53);
            }
            geoService.removeRunnerPos(agenid, workerId);
        }
        HuawuWorker huawuWorker = new HuawuWorker();
        huawuWorker.setUserId(workerId);
        if (state != null && state.intValue() == -1) {
            huawuWorker.setWorkerState(0);//解聘
        } else {
            huawuWorker.setWorkerState(-1);//解聘
        }

        int modifyMfoyouWorkerInfo = iIdentity.modifyMfoyouWorkerInfo(huawuWorker);
        return JsonRet.buildSuccRet(modifyMfoyouWorkerInfo - 1);
    }

    /**
     * 添加区域
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "addRegionInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> addRegionInfo(@Context HttpServletRequest request, String json) {
        logger.info(json);
        MfoyouRegionCustom parseObject = JSON.parseObject(json, MfoyouRegionCustom.class);
        parseObject.setAgentId(sessionService.currentUserId(request));
        int ret = iOrder.addRegionCustom(parseObject);
        return JsonRet.buildRet(ret - 1);
    }

    /**
     * 更新区域信息
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "updateRegionInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> updateRegionInfo(@Context HttpServletRequest request, String json) {
        MfoyouRegionCustom parseObject = JSON.parseObject(json, MfoyouRegionCustom.class);
        parseObject.setAgentId(sessionService.currentUserId(request));
        int ret = iOrder.updateRegionCustom(parseObject);
        return JsonRet.buildRet(ret - 1);
    }

    /**
     * 删除区域信息
     *
     * @param request
     * @param regionId
     * @return
     */
    @GET
    @Path(value = "deleteRegionInfo")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> deleteRegionInfo(@Context HttpServletRequest request, @QueryParam("regionId") Integer regionId) {
        int ret = iOrder.deleteRegionCustom(regionId);
        return JsonRet.buildRet(ret - 1);
    }

    /**
     * 获取所有区域
     *
     * @param request
     * @return
     */
    @GET
    @Path(value = "getRegionInfos")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> getRegionInfos(@Context HttpServletRequest request) {
        Integer agentId = sessionService.currentUserId(request);
        List<MfoyouRegionCustom> customRegionListByAgentId = iOrder.getCustomRegionListByAgentId(agentId);
        List<Integer> stationIds = customRegionListByAgentId.stream().map((MfoyouRegionCustom mfo) -> mfo.getStationId()).collect(Collectors.toList());
        List<MfoyouStationMaster> masters = iIdentity.getStationByStationIds(stationIds);
        Map<Integer, MfoyouStationMaster> collect = masters.stream().
                collect(Collectors.toMap((MfoyouStationMaster ms) -> ms.getStationId(),
                        (MfoyouStationMaster ms) -> ms));
        customRegionListByAgentId.stream().forEach((MfoyouRegionCustom mfo) -> {
            if (mfo.getStationId() != null) {
                mfo.setMfoyouStationMaster(collect.get(mfo.getStationId()));
            }
        });
        return JsonRet.buildSuccRet(customRegionListByAgentId);
    }

    /**
     * 添加区域信息
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "addStation")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> registStation(@Context HttpServletRequest request, String json) {
        Integer agentId = sessionService.currentUserId(request);
        MfoyouMap mfoyouMap = Json2Object.json2MfoyouMap(json);
        String phone = mfoyouMap.get("phone");
        HuawuUser userInfoByPhone = iAccount.getUserInfoByPhone(phone, -3);
        if (userInfoByPhone != null) {
            return JsonRet.buildRet(-3001);
        }
        String passwd = mfoyouMap.get("passwd");
        String name = mfoyouMap.get("name");
        Integer shareRun = mfoyouMap.getInteger("runnerShare");
        Integer storeShareFee = mfoyouMap.getInteger("storeShare");
        Integer powerState = mfoyouMap.getInteger("powerState");
        HuawuUser huawuUser = new HuawuUser();
        huawuUser.setUserPhone(phone);
        huawuUser.setUserPassword(passwd);
        huawuUser.setAgentId(-3);
        HuawuUser registUser = accountService.registUser(huawuUser);
        MfoyouStationMaster mfoyouStationMaster = new MfoyouStationMaster();
        mfoyouStationMaster.setAgentId(agentId);
        mfoyouStationMaster.setStationLoginNumber(phone);
        mfoyouStationMaster.setStationId(registUser.getUserId());
        mfoyouStationMaster.setStationName(name);
        mfoyouStationMaster.setStoreShareFee(storeShareFee);
        mfoyouStationMaster.setRunnerShareFee(shareRun);
        mfoyouStationMaster.setPowerState(powerState);
        int ret = iIdentity.addStation(mfoyouStationMaster);
        String area = mfoyouMap.get("agentCoordinateArea");
        if (ret == 1 && area != null) {
            MfoyouRegionCustom mfoyouRegionCustom = new MfoyouRegionCustom();
            mfoyouRegionCustom.setAgentCoordinateArea(area);
            mfoyouRegionCustom.setStationId(registUser.getUserId());
            mfoyouRegionCustom.setAgentId(sessionService.currentUserId(request));
            iOrder.addRegionCustom(mfoyouRegionCustom);
        }
        return JsonRet.buildRet(ret - 1);
    }

    /**
     * 获取通知公告  ，有空用redis挡下
     *
     * @param request
     * @param agentId
     * @return
     */
    @GET
    @Path(value = "getNotice")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.ALLACCESS)
    public JsonRet<?> getServiceNotice(@Context HttpServletRequest request, @QueryParam("agentId") Integer agentId) {
        if (agentId == null) {
            return JsonRet.buildRet(-96);
        }
        HuawuServiceNotice huawuServiceNotice = iIdentity.getServiceNotice(agentId);
        return JsonRet.buildSuccRet(huawuServiceNotice);
    }

    /**
     * 编辑通告
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "modifyNotice")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> modifyServiceNotice(@Context HttpServletRequest request, String json) {
        Integer agentId = sessionService.currentUserId(request);
        HuawuServiceNotice json2Object = Json2Object.json2Object(json, HuawuServiceNotice.class);
        json2Object.setAgentId(agentId);
        iIdentity.modifyServiceNotice(json2Object);
        return JsonRet.buildSuccRet(null);
    }

    /**
     * 添加服务商组件
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "addServiceComponent")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> addServiceComponent(@Context HttpServletRequest request, String json) {
        Integer agentId = sessionService.currentUserId(request);
        HuawuServiceComponent json2Object = Json2Object.json2Object(json, HuawuServiceComponent.class);
        json2Object.setAgentId(agentId);
        iIdentity.addServiceComponent(json2Object);
        return JsonRet.buildSuccRet(null);
    }

    /**
     * 删除服务商组件
     *
     * @param request
     * @param json
     * @return
     */
    @POST
    @Path(value = "updateServiceComponent")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> updateServiceComponent(@Context HttpServletRequest request, String json) {
        Integer agentId = sessionService.currentUserId(request);
        HuawuServiceComponent json2Object = Json2Object.json2Object(json, HuawuServiceComponent.class);
        json2Object.setAgentId(agentId);
        iIdentity.updateServiceComponent(json2Object);
        return JsonRet.buildSuccRet(null);
    }

    /**
     * 获取所有服务商组件
     *
     * @param request
     * @param componentId
     * @return
     */
    @GET
    @Path(value = "getAllServiceComponent")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> getAllServiceComponent(@Context HttpServletRequest request, @QueryParam("componentId") Integer componentId) {
        Integer agentId = sessionService.currentUserId(request);
        List<HuawuServiceComponent> huawuServiceComponents = iIdentity.getServiceComponentByAgentId(agentId, null, componentId);
        return JsonRet.buildSuccRet(huawuServiceComponents);
    }

    /**
     * 删除服务商组件
     *
     * @param request
     * @param componentId
     * @return
     */
    @GET
    @Path(value = "deleteServiceComponent")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> deleteServiceComponent(@Context HttpServletRequest request, @QueryParam("componentId") Integer componentId) {
        Integer agentId = sessionService.currentUserId(request);
        int ret = iIdentity.deleteServiceComponent(componentId, agentId);
        return JsonRet.buildRet(ret - 1);
    }

    /**
     * 获取店铺排序
     *
     * @param request
     * @param phoneNumber
     * @return
     */
    @GET
    @Path(value = "getSortKey")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> getSortKey(@Context HttpServletRequest request, @QueryParam("phoneNumber") String phoneNumber) {
        Integer agentId = sessionService.currentUserId(request);
        Map<String, Object> list = iIdentity.getSortKey(agentId, phoneNumber);
        return JsonRet.buildSuccRet(list);
    }

    /**
     * 取消店铺排序
     *
     * @param request
     * @param storeId
     * @return
     */
    @GET
    @Path(value = "unsetSortKey")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> unsetSortKey(@Context HttpServletRequest request, @QueryParam("storeId") Integer storeId) {
        Integer agentId = sessionService.currentUserId(request);
        int ret = iIdentity.unsetSortKey(agentId, storeId);
        return JsonRet.buildRet(ret - 1);
    }

    /**
     * 设置排序位置
     *
     * @param request
     * @param storeId
     * @param key
     * @return
     */
    @GET
    @Path(value = "setSortKey")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> setSortKey(@Context HttpServletRequest request, @QueryParam("storeId") Integer storeId, @QueryParam("key")
            Integer key) {
        Integer agentId = sessionService.currentUserId(request);
        int ret = iIdentity.setSortKey(agentId, storeId, key);
        return JsonRet.buildRet(ret - 1);
    }

    /**
     * 指派订单
     *
     * @param request
     * @param response
     * @param orderId
     * @param userId
     * @return
     */
    @POST
    @Path(value = "/transfer/gain/{userId}/{orderId}")
    @Produces("application/json;charset=UTF-8")
    @UrlRight({UserRight.AGENTACCESS, UserRight.STATIONMASTER})
    public JsonRet<?> transferOrderToRunerGain(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("orderId") Integer orderId, @PathParam("userId") Integer userId) {
        HuawuServiceOrder order = iOrder.getServiceOrderInfo(orderId);
        HuawuWorker worker = iAccount.getWorkerInfo(order.getServiceOrderReceiveUser());
        String workPhone = worker.getWorkerPhone();
        String workName = worker.getWorkerName();
        Boolean bRet = serviceOrderService.transferOrderToRuner(request, userId, orderId);
        if (bRet) {
            xgPushSerivce.transferPushNoticeToUser(userId, orderId, 1, 101,
                    "已转派订单提醒", "由管理员将" + workPhone + "(" + workName + ")的订单成功转单给你");
        }
        return JsonRet.buildRet(bRet ? 0 : -92, bRet);
    }

    /**
     * 新需求商城配置
     *
     * @param request
     * @param response
     * @param json
     * @return
     */
    @POST
    @Path("shopSetting")
    @Produces("application/json;charset=UTF-8")
    @UrlRight(UserRight.AGENTACCESS)
    public JsonRet<?> shopSetting(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                  String json) {
        logger.info("商城配置请求json数据：" + json);
        int agentId = sessionService.currentUserId(request);
        MfoyouMap json2MfoyouMap = Json2Object.json2MfoyouMap(json);
        HuawuAgentStoreSetting storeSetting = new HuawuAgentStoreSetting();
        storeSetting.setAgentId(agentId);
        storeSetting.setStoreName(json2MfoyouMap.get("storeName"));
        storeSetting.setStoreLogoUrl(json2MfoyouMap.get("storeLogo"));
        storeSetting.setStorePhone(json2MfoyouMap.get("storePhone"));
        storeSetting.setRechageType(json2MfoyouMap.getInteger("rechageType"));//1：微信提现	2：支付宝提现
        storeSetting.setShowType(json2MfoyouMap.getInteger("showType"));//0:商家自行设置 1：统一外卖版 2：统一零售版
        storeSetting.setModifyTime(new Date());
        storeSetting.setIsClose(json2MfoyouMap.getInteger("isClose"));
        int result = iIdentity.updateMfoyouAgentShopSetting(storeSetting);
        return result == 1 ? JsonRet.buildRet(0) : JsonRet.buildRet(-11);
    }
}
